var Protocol = require("../Controls/Protocol")
const moment = require("../miniprogram_npm/moment/index.js")

const orderRule = {
  amount: 'int',
  body: 'string'
}

var forWaitTradeId = -1;
var forWaitOptHandler = {};

const queryOrderResultHandler = 
{
  success: (res)=>
  {
    console.log("查询账单结果");
    console.log(res.data);
    const data = res.data.data;
    if(data.paid)
    {
      if(forWaitOptHandler.success)
      {
        forWaitOptHandler.success()
      }
    }
    else
    {
      if(forWaitOptHandler.fail)
      {
        forWaitOptHandler.fail();
      }
    }
  },
  fail: (res) =>
  {
    if (forWaitOptHandler.fail) {
      forWaitOptHandler.fail();
    }
  },
  complete:()=>
  {
    forWaitTradeId = -1;
  }
}

const wxpaymentResultHandler = 
{
  success: (res)=>
  {
    console.log("查询账单");
    Protocol.queryOrder(forWaitTradeId, queryOrderResultHandler);
  },
  fail: (res)=>
  {
    forWaitTradeId = -1;
    if (forWaitOptHandler.fail) {
      forWaitOptHandler.fail();
    }
  }
}

module.exports = (order, optHandler) =>{
  const now = moment();
  const timeStamp = Math.ceil((now.valueOf() / 1000)).toString();
  forWaitOptHandler = optHandler;

  Object.assign(order, {timeStamp});
  Protocol.placeOrder(order, {
    success:(res)=>
    {
      const data = res.data.data;
      if(data.isOk == true)
      {
        forWaitTradeId = data.tradeId;

        wx.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonce_str,
          package: 'prepay_id='+data.prepay_id,
          signType: 'md5',
          paySign: data.paySign,
          success: wxpaymentResultHandler.success,
          fail: wxpaymentResultHandler.fail
        })
      }
    },
    fail:(res)=>
    {
      if (forWaitOptHandler.fail)
      {
        forWaitOptHandler.fail();
      }
    }
  });
}